﻿using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;

using GroupChallenge.Web;
using GroupChallenge.Web.Services;

namespace GroupChallenge
{
    public partial class QuestionsView : Page
    {
        #region Initialization
        public QuestionsView()
        {
            InitializeComponent();

            this.Title = ApplicationStrings.SubmitQuestionViewTitle;

            Loaded += new RoutedEventHandler(QuestionsView_Loaded);
        }

        void QuestionsView_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshList();
        }

        #endregion                              // Initialization

        #region UI Events

        private void InsertUpdateQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            // Get all values to an XML file.
            QuestionsViewModel questionViewModel = LayoutRoot.DataContext as QuestionsViewModel;
            if (null != questionViewModel)
            {
                questionViewModel.InsertUpdateQuestion();
            }
        }

        private void DeleteQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            DeleteQuestion();
        }

        private void Populate_Click(object sender, RoutedEventArgs e)
        {
            PopulateWithSample();
        }

        private void RefreshList_Click(object sender, RoutedEventArgs e)
        {
            RefreshList();
        }

        private void QuestionsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CopySelectedRIAQuestionToWSQuestion();
        }

        private void SaveAllQuestionsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                GroupChallengeDomainContext groupChallengeDomainContext = new GroupChallengeDomainContext();

                var query = groupChallengeDomainContext.SaveQuestionsQuery();
                groupChallengeDomainContext.Load(query, CompletedSaveAllQuestions, true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Unable to save the questions.\r\n\r\nReason: " + ex.Message, "Save Questions Error", MessageBoxButton.OK);
            }
        }

        private void SetCurrentQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            Button clickedButton = sender as Button;
            if (null != clickedButton &&
                clickedButton.Content is int)
            {
                int questionId = (int)clickedButton.Content;

                SetCurrentQuestion(questionId);
            }
        }

        #endregion                              // UI Events

        #region Private Methods

        private void DeleteQuestion()
        {
            QuestionsViewModel questionViewModel = LayoutRoot.DataContext as QuestionsViewModel;
            if (null != questionViewModel)
            {
                if (questionViewModel.CurrentQuestion.QuestionId != 0)
                {
                    GroupChallengeDomainContext groupChallengeDomainContext = new GroupChallengeDomainContext();

                    groupChallengeDomainContext.DropQuestion(questionViewModel.CurrentQuestion.QuestionId, CompletedDropQuestion, null);
                }
            }
        }

        private void PopulateWithSample()
        {
            QuestionsViewModel questionViewModel = LayoutRoot.DataContext as QuestionsViewModel;
            if (null != questionViewModel)
            {
                questionViewModel.CurrentQuestion.QuestionText = "What does the acronym, INPC, mean?";
                questionViewModel.CurrentQuestion.Answer1 = "In-Process Controls";
                questionViewModel.CurrentQuestion.Answer2 = "INotifyProperty";
                questionViewModel.CurrentQuestion.Answer3 = "IKnowOfNoPropertyChange";
                questionViewModel.CurrentQuestion.Answer4 = "INotifyPropertyChanged";
                questionViewModel.CurrentQuestion.CategoryName = "Data Binding";

                // Status: Sending in new value, then the old value.
                questionViewModel.CurrentQuestion.CorrectAnswerId = 1;

                questionViewModel.CurrentQuestion.QuestionTypeId = (GroupChallengeSvc.QuestionType)QuestionType.MultipleChoice;
            }
        }

        private void CompletedDropQuestion(InvokeOperation invokeOperation)
        {
            if (invokeOperation.HasError)
            {
                invokeOperation.MarkErrorAsHandled();

                MessageBox.Show("Unable to delete the question specified question.\r\n\r\nReason: " + invokeOperation.Error.Message, "Delete Question Error", MessageBoxButton.OK);
            }
            else
            {
                MessageBox.Show("Deleted the question.", "Delete Question Success", MessageBoxButton.OK);

                // Quick Refresh to get the correct questions listed.
                RefreshList();
            }
        }

        private void RefreshList()
        {
            GroupChallengeDomainContext groupChallengeDomainContext = new GroupChallengeDomainContext();

            var query = groupChallengeDomainContext.GetQuestionsQuery();

            QuestionsDataGrid.ItemsSource = groupChallengeDomainContext.Questions;

            groupChallengeDomainContext.Load(query, CompletedListLoad, true);
        }

        private void CompletedListLoad(LoadOperation loadOperation)
        {
            if (loadOperation.HasError)
            {
                loadOperation.MarkErrorAsHandled();

                MessageBox.Show("Unable to retrieve the question list.\r\n\r\nReason: " + loadOperation.Error.Message, "List Load Error", MessageBoxButton.OK);
            }
        }

        private void CopySelectedRIAQuestionToWSQuestion()
        {
            QuestionsViewModel questionViewModel = LayoutRoot.DataContext as QuestionsViewModel;
            GroupChallenge.Web.Question riaQuestion = QuestionsDataGrid.SelectedItem as GroupChallenge.Web.Question;

            if (null != questionViewModel &&
                null != riaQuestion)
            {
                questionViewModel.Clear();
                questionViewModel.CurrentQuestion.QuestionId = riaQuestion.QuestionId;
                questionViewModel.CurrentQuestion.QuestionText = riaQuestion.QuestionText;
                questionViewModel.CurrentQuestion.Answer1 = riaQuestion.Answer1;
                questionViewModel.CurrentQuestion.Answer2 = riaQuestion.Answer2;
                questionViewModel.CurrentQuestion.Answer3 = riaQuestion.Answer3;
                questionViewModel.CurrentQuestion.Answer4 = riaQuestion.Answer4;
                questionViewModel.CurrentQuestion.CategoryName = riaQuestion.CategoryName;
                questionViewModel.CurrentQuestion.CorrectAnswerId = riaQuestion.CorrectAnswerId;
                questionViewModel.CurrentQuestion.QuestionTypeId = (GroupChallengeSvc.QuestionType)riaQuestion.QuestionTypeId;
            }
        }

        private void CompletedSaveAllQuestions(LoadOperation loadOperation)
        {
            if (loadOperation.HasError)
            {
                loadOperation.MarkErrorAsHandled();

                MessageBox.Show("Unable to save the questions.\r\n\r\nReason: " + loadOperation.Error.Message, "Save Questions Error", MessageBoxButton.OK);
            }
            else
            {
                if (null != loadOperation.Entities)
                {
                    FriendlyResult friendlyResult = loadOperation.Entities.FirstOrDefault() as FriendlyResult;
                    if (null != friendlyResult)
                    {
                        if (friendlyResult.ResultId == 1)         // Success
                            MessageBox.Show(friendlyResult.FriendlyText, "Success", MessageBoxButton.OK);
                        else
                            MessageBox.Show(friendlyResult.FriendlyText, "Failure", MessageBoxButton.OK);
                    }
                }
            }
        }

        private void SetCurrentQuestion(int questionId)
        {
            if (questionId == 0)
            {
                MessageBox.Show("Invalid question id.  Unable to set the current question.", "Set Current Questions Error", MessageBoxButton.OK);
            }
            else
            {
                try
                {
                    GroupChallengeDomainContext groupChallengeDomainContext = new GroupChallengeDomainContext();

                    var query = groupChallengeDomainContext.SetCurrentQuestionQuery(questionId);
                    groupChallengeDomainContext.Load(query, CompletedSetCurrentQuestion, true);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Unable to set the current question.\r\n\r\nReason: " + ex.Message, "Set Current Questions Error", MessageBoxButton.OK);
                }
            }
        }

        private void CompletedSetCurrentQuestion(LoadOperation loadOperation)
        {
            if (loadOperation.HasError)
            {
                loadOperation.MarkErrorAsHandled();

                MessageBox.Show("Unable to set the current question.\r\n\r\nReason: " + loadOperation.Error.Message, "Set Current Questions Error", MessageBoxButton.OK);
            }
            else
            {
                if (null != loadOperation.Entities)
                {
                    FriendlyResult friendlyResult = loadOperation.Entities.FirstOrDefault() as FriendlyResult;
                    if (null != friendlyResult)
                    {
                        // Show the current question now.
                        CurrentQuestionId.Text = friendlyResult.ResultId.ToString();
                    }
                }
            }
        }

        #endregion                              // Private Methods
    }
}